package cn.chenwx.bbsforum.controller;

import cn.chenwx.bbsforum.component.StringAndArray;
import cn.chenwx.bbsforum.entity.Article;
import cn.chenwx.bbsforum.entity.Tag;
import cn.chenwx.bbsforum.entity.User;
import cn.chenwx.bbsforum.service.ArticleService;
import cn.chenwx.bbsforum.service.CommentService;
import cn.chenwx.bbsforum.service.TagService;
import cn.chenwx.bbsforum.service.UserService;
import cn.chenwx.bbsforum.utils.*;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.Null;
import java.io.File;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller

public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private CommentService commentService;

    @GetMapping("/user/home")
    public String user(HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user==null){
            return "redirect:login";
        }

        return "user";
    }

    /**
     * 上传头像
     */
    @PostMapping(value = "/user/uploadHead")
    @ResponseBody
    public BlogJSONResult uploadHead(HttpServletRequest request,HttpSession session) {
        User user = (User) session.getAttribute("user");
        String username = user.getUsername();
        String img = request.getParameter("img");
        //获得上传文件的后缀名
        int index = img.indexOf(";base64,");
        String strFileExtendName = "." + img.substring(11,index);
        img = img.substring(index + 8);
        try {
            FileUtil fileUtil = new FileUtil();
            //文件路径名
            String filePath = this.getClass().getResource("/").getPath().substring(1) + "userImg/";
            //文件名时间戳
            TimeUtil timeUtil = new TimeUtil();
            //文件base64转File类型(路径，后缀，文件名)
            File file = fileUtil.base64ToFile(filePath, img, timeUtil.getLongTime() + strFileExtendName);
            String url = fileUtil.uploadFile(file, "user/avatar/" + username);
            int userId = userService.findUserByName(username).getId();
            userService.updateAvatarImgUrlById(url, userId);
            BlogJSONResult data = userService.getHeadPortraitUrl(userId);
            return data;
        } catch (Exception e){
            e.printStackTrace();
            return BlogJSONResult.errorMsg("更改头像失败");
        }
    }

    /**
     * 获得个人资料
     */
    @PostMapping(value = "/user/getUserPersonalInfo")
    @ResponseBody
    public BlogJSONResult getUserPersonalInfo(HttpSession session) {
        String username = (String) session.getAttribute("username");
        BlogJSONResult data = userService.getUserPersonalInfoByUsername(username);
        return data;
    }

    /**
     * 保存(更新)个人资料
     */
    @PostMapping(value = "/user/savePersonalDate")
    @ResponseBody
    public BlogJSONResult savePersonalDate(User user, HttpSession session){
        String username = (String) session.getAttribute("username");
        return userService.savePersonalDate(user, username);

    }
    /**
     * 获得该用户曾今的所有评论
     */
    @PostMapping(value = "/user/getUserComment")
    @ResponseBody
    public BlogJSONResult getUserComment(@RequestParam("rows") String rows,
                                         @RequestParam("pageNum") String pageNum,
                                        HttpSession session){
        String username = (String) session.getAttribute("username");
        BlogJSONResult data = commentService.getUserComment(Integer.parseInt(rows), Integer.parseInt(pageNum), username);
        return data;
    }

    /**
     * 获得用户未读消息
     */
    @PostMapping(value = "/user/getUserNews")
    @ResponseBody
    public BlogJSONResult getUserNews(HttpSession session){
        String username = (String) session.getAttribute("username");
        if (username!=null){
        BlogJSONResult data = commentService.getUserComments(username);
            return data;
        }
        return null;

    }
    /**
     * 获得该用户曾今的所有留言
     */
    @PostMapping(value = "/user/getUserLeaveWord")
    @ResponseBody
    public BlogJSONResult getUserLeaveMessage(@RequestParam("rows") String rows,
                                              @RequestParam("pageNum") String pageNum,
                                            HttpSession session){
        String username = (String) session.getAttribute("username");
        BlogJSONResult data = commentService.getUserComment(Integer.parseInt(rows), Integer.parseInt(pageNum), username);
        return data;
    }

    @GetMapping("/user/edit")
    public String userEdit (HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user==null){
            return "redirect:login";
        }
        return "edit";

    }


    @Autowired
    private TagService tagService;
    /*
        从数据库中查找标签
     */
    @GetMapping("/user/getTags")
    @ResponseBody
    public Map userGetTags(){
        PageInfo<Tag> tagPageInfo = new PageInfo<>(tagService.findTagsCloud());
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        map.put("data",tagPageInfo.getList());
        map.put("count",tagPageInfo.getTotal());
        return map;
    }


    @Autowired
    private ArticleService articleService;
    @PostMapping(value = "/user/publish", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public BlogJSONResult publishArticle(Article article, HttpServletRequest request, HttpSession session){
        //获得文章html代码并生成摘要

        String articleHtmlContent = request.getParameter("content");
        article.setContent(articleHtmlContent);
        article.setArticleTabloid(articleHtmlContent+"...");
        String articleTag = request.getParameter("tag");
        //添加标签
        User  user =  (User)session.getAttribute("user");
        article.setUserId(user.getId());
        articleService.addArticle(article);
        return BlogJSONResult.ok(article);
    }


}
